package unit2.authorization;

import java.io.IOException;

import unit2.user.Admin;
import unit2.Input;
import unit2.user.User;
import unit2.db.Users;
import unit2.creater.CreaterUsers;

public class Authorization {	
	
	public Authorization() throws ClassNotFoundException, IOException{
	}
	
	private User findInDB(String nameOfUser, Users dbOfUsers){
		//here maybe be NULL
		User foundUser=  dbOfUsers.findUser(nameOfUser);
		//if(foundUser!=null){
			return foundUser;
	//	}
		//else 
	}

	public User initUser(Users dbOfUsers) throws ClassNotFoundException, IOException{
		Input action= new Input();
		switch(action.getLine()){
		
		case "find" :{
		  return findInDB(dbOfUsers);
			}
		case "new" :{
			return makeNewUser(dbOfUsers);
			}
		case "magic Button":{
			return makeAdmin(dbOfUsers);
		}
		case "exit":{
			System.exit(0);
			}
		}
		
		return null;
		
	}
	
	private User makeNewUser(Users dbOfUsers) throws ClassNotFoundException, IOException{
		User newUser =new User();
		newUser.setName();
		//catch exception
		dbOfUsers=CreaterUsers.readUsersFromFile();
		dbOfUsers.addUser(newUser);
		CreaterUsers.writeUsersInFile(dbOfUsers);
		return newUser;
	}
	
	//to do  copyofcode
	private User makeAdmin(Users dbOfUsers) throws ClassNotFoundException, IOException{
		Admin newUser =new Admin();
		newUser.setName();
		//catch exception
		dbOfUsers=CreaterUsers.readUsersFromFile();
		dbOfUsers.addUser(newUser);
		CreaterUsers.writeUsersInFile(dbOfUsers);
		return newUser;
	}
	
	//to do catch null user
	private User findInDB(Users dbOfUsers) throws ClassNotFoundException, IOException{
		dbOfUsers=CreaterUsers.readUsersFromFile();
		User userFromDB= new User();
		userFromDB =findInDB(initName(), dbOfUsers);
		return userFromDB;
	}
	
	private String initName(){
	Input A= new Input();	
	return A.getLine();
	}
}

